package net.obxlabs.tweetpad.stats;

import net.silentlycrashing.util.*;
import processing.core.*;

public class SourceLine {
	public static final int LENGTH = 80;
	public static final int NUM_PTS = 7;
	public static final int SRC_PT = 3;
	public static final float ROUNDING_SCALAR = 0.75f;
	public static final int ANIM_DURATION = 60;
	
	private PApplet p;
	private int baseLineY;
	private int unitSize;
	private int color;
	private AnimatedPoint[] points;
	
	/** 
	 * Builds a SourceLine with random stroke color and weight.
	 *  
	 * @param p the parent PApplet
	 * @param y the baseline value
	 * @param u the source unit size
	 * @param x the x start value
	 * @param i the index
	 */
	public SourceLine(PApplet p, int y, int u, int x, int i) {
		this(p, y, u, x, i, p.color(MiscMath.randRange(100, 150)));
	}
	
	/**
	 * Builds a SourceLine.
	 * 
	 * @param p the parent PApplet
	 * @param y the baseline value
	 * @param u the source unit size
	 * @param x the x start value
	 * @param i the index
	 * @param color the fill color
	 */
	public SourceLine(PApplet p, int y, int u, int x, int i, int color) {
		this.p = p;
		
		// set the line properties
		baseLineY = y;
		unitSize = u;
		this.color = color;

		points = new AnimatedPoint[NUM_PTS];
		
		// init the points
		points[0] = new AnimatedPoint(i*LENGTH+x, baseLineY);
		points[1] = new AnimatedPoint(i*LENGTH+x+5, baseLineY);
		points[2] = new AnimatedPoint(i*LENGTH+x+5+5, baseLineY);
		points[3] = new AnimatedPoint(i*LENGTH+x+5+5+30, baseLineY);
		points[4] = new AnimatedPoint(i*LENGTH+x+5+5+30+30, baseLineY);
		points[5] = new AnimatedPoint(i*LENGTH+x+5+5+30+30+5, baseLineY);
		points[6] = new AnimatedPoint(i*LENGTH+x+5+5+30+30+5+5, baseLineY);
		
		p.registerPre(this);
	}
	
	public synchronized void pre() {
    	for (int i=0; i < NUM_PTS; i++) {
    		points[i].pre();
    	}
    }
	
	public void addSourceCount() {
		points[SRC_PT-1].moveTo(points[SRC_PT-1].x, points[SRC_PT-1].y+unitSize*ROUNDING_SCALAR, ANIM_DURATION);
		points[SRC_PT].moveTo(points[SRC_PT].x, points[SRC_PT].y+unitSize, ANIM_DURATION);
		points[SRC_PT+1].moveTo(points[SRC_PT+1].x, points[SRC_PT+1].y+unitSize*ROUNDING_SCALAR, ANIM_DURATION);
	}
	
	public void subSourceCount() {
		points[SRC_PT-1].moveTo(points[SRC_PT-1].x, points[SRC_PT-1].y-unitSize*ROUNDING_SCALAR, ANIM_DURATION);
		points[SRC_PT].moveTo(points[SRC_PT].x, points[SRC_PT].y-unitSize, ANIM_DURATION);
		points[SRC_PT+1].moveTo(points[SRC_PT+1].x, points[SRC_PT+1].y-unitSize*ROUNDING_SCALAR, ANIM_DURATION);
	}
	
	/**
	 * Draws the StatLine.
	 */
	public void draw() {
		p.fill(color);
		p.noStroke();
		p.beginShape();
		for (int i=0; i < NUM_PTS; i++) {
			p.curveVertex(points[i].x, points[i].y);
		}
		p.vertex(points[0].x, points[0].y);
		p.endShape();
	}
	
	public void reset() {
		for (int i=0; i < NUM_PTS; i++) {
			points[i].moveTo(points[i].x, baseLineY, ANIM_DURATION);
		}
	}
}
